package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import com.nus.database.DBAdaptor;
import com.nus.parsers.NdroidAPI;
import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleNews;
import com.nus.representations.RemindDetails;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class OptionsActivity extends Activity{
	public static ProgressDialog pd;
	public static String uname;
	// public static Handler handler;
	public ImageButton ivle;
	public ImageButton news;
	public ImageButton library;
	public ImageButton events;
	public ImageButton sports;
	public ImageButton other;
	public ImageButton emergency;
	public ImageButton careercenter;
	public ImageButton shuttlemap;
	public ImageButton connect;
	private SoundManager msoundManager;
	public static int i = 0;
	//protected TextView title;
	private ArrayList<String> remainder_data;//=new ArrayList<String>();
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.optionslayout);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_titlemain);
		// title = (TextView) findViewById(R.id.titleheader);
		// title.setText("NdroidUS");
		TextView tvname = (TextView) findViewById(R.id.menu);
		uname = NdroidAPI.getName();
		tvname.setText("Welcome:" + uname);
		ivle = (ImageButton) findViewById(R.id.workspace);
		ivle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startLoadingNew("Loading Workspace");
				startActivity(new Intent("com.nus.IvleModuleActivity"));
			}
		});
		boolean netconn = checkInternetConnection();
		if (!netconn) {
			Toast.makeText(getApplicationContext(),
					"Please check your internet or 3G connection",
					Toast.LENGTH_LONG).show();
		}
		news = (ImageButton) findViewById(R.id.news);
		emergency = (ImageButton) findViewById(R.id.emergency);
		msoundManager = new SoundManager();
		msoundManager.initSounds(getBaseContext());
		msoundManager.addSound(1, R.raw.click);
		news.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				msoundManager.playSound(1);
				startLoadingNew("Loading NUS News");
				startActivity(new Intent("com.nus.IvleNewsActivity"));
			}
		});

		sports = (ImageButton) findViewById(R.id.sports);
		sports.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				msoundManager.playSound(1);
				startActivity(new Intent("com.nus.SportsActivity"));
				
			}
		});
		connect = (ImageButton) findViewById(R.id.connect);
		connect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				msoundManager.playSound(1);
				startLoadingNew("Loading NUS Connect");
				startActivity(new Intent("com.nus.chat.XMPPClient"));
			}
		});
		events = (ImageButton) findViewById(R.id.events);
		events.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// if(i==1)
				// com.nus.IvleStudentEventActivity.finish();
				msoundManager.playSound(1);
				startLoadingNew("Loading Events");
				startActivity(new Intent("com.nus.IvleStudentEventActivity").putExtra(
						"IVLE_Token", NUS_Android.IVLE_Token));
				
				// startActivity(new
				// Intent("com.nus.IvleStudentEventActivity").putExtra("IVLE_Token",
				// NUS_Android.IVLE_Token));

				// startActivity(new
				// Intent("com.nus.IvleStudentEventActivity"));
			}
		});

		emergency = (ImageButton) findViewById(R.id.emergency);
		emergency.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				msoundManager.playSound(1);
				startActivity(new Intent("com.nus.EmergencyContact"));

				// startActivity(new
				// Intent("com.nus.IvleStudentEventActivity"));
			}
		});
		careercenter = (ImageButton) findViewById(R.id.careercenter);
		careercenter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				msoundManager.playSound(1);
				startActivity(new Intent("com.nus.CareerCenter"));

				// startActivity(new
				// Intent("com.nus.IvleStudentEventActivity"));
			}
		});
		shuttlemap = (ImageButton) findViewById(R.id.shuttlemap);
		shuttlemap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				msoundManager.playSound(1);
				startActivity(new Intent("com.nus.Shuttle_Map_Activity"));

			}
		});
		NUS_Android.pd.dismiss();
	}

	public void onBackPressed() {
		this.finish();
		msoundManager.playSound(1);
		// startActivity(new Intent("com.nus.OptionsActivity"));
		// android.os.Process.killProcess(android.os.Process.myPid());
		onDestroy();
		return;
	}
	public void startLoadingNew(String msg) {
		
		pd = ProgressDialog.show(OptionsActivity.this, msg,
				"Please wait ...", true);
		
		pd.setIcon(R.drawable.header);
		// return super.onKeyDown(keyCode, event);
	}
	public void startLoading(String msg) {
		
		pd = ProgressDialog.show(OptionsActivity.this, msg,
				"Please wait ...", true);
		
		

		// return super.onKeyDown(keyCode, event);
	}

	

	public static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();

		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.close_app, menu);
		
		return true;
	}/* End of onCreateOptionsMenu */

	public boolean onOptionsItemSelected(MenuItem item) {
		// ActivityManager activityManager = (ActivityManager)
		// getSystemService(ACTIVITY_SERVICE);
		// activityManager.killBackgroundProcesses("com.nus");
		switch (item.getItemId()) {
		//case R.id.CloseLogo : onDestroy(); break;
		case R.id.ReminderLogo : displayReminders() ; break;
		}

		
		return false;
	}
	private void displayReminders(){
		DBAdaptor db = new DBAdaptor(this);
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
        Calendar cal = Calendar.getInstance();
        remainder_data=new ArrayList<String>();
        db.open();
        Cursor c = db.getAllRemainders();
        
        long now3=System.currentTimeMillis();
        if (c.moveToFirst())
        {
            do { 
            	long remainder_time=c.getLong(3);
            	cal.setTimeInMillis(remainder_time);
            	Log.i(" database activity"," time from db is"+df.format(cal.getTime())+" in milli is"+remainder_time);
            	cal.setTimeInMillis(now3);
            	Log.i("database activity","time now in milli is"+now3+" other wise is"+df.format(cal.getTime()));
            	if(remainder_time<now3 ){
            		db.deleteRemainder(remainder_time);
            	} else {
                DisplayRemainder(c);
            	}
            } while (c.moveToNext());
        }
        db.close();
        Dialog dialog = new Dialog(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("    ---Remainders---");
        builder.setIcon(R.drawable.timetable);
       ListView list=  new ListView(this);
//        ListView list =(ListView)findViewById(R.id.reminder_view);
       
        list.setAdapter(new ArrayAdapter<String>(this,
        		android.R.layout.simple_list_item_1, remainder_data));
        builder.setView(list);
        dialog = builder.create();
        dialog.show();
	}
	
	private void DisplayRemainder(Cursor c) {
		 DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
		 StringBuffer rem_data=new StringBuffer();
		// rem_data.append(c.getString(1));
		 rem_data.append(c.getString(2)+" : ");
		 rem_data.append(df.format(c.getLong(3)).toString());
		 remainder_data.add(rem_data.toString());
//		 remainder_data.add(c.getString(2));
		 
//		
//		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
//       builder.setMessage("Reminders set are  "+"\""+c.getString(1)+" "+c.getString(2)+" "+df.format(c.getLong(3))+"\"")
//       .setCancelable(false)
//       .setPositiveButton("ok", new DialogInterface.OnClickListener() {
//           public void onClick(DialogInterface dialog, int id) {
//          	 
//           }
//
//			public OnClickListener setNegativeButton(String string,
//					OnClickListener onClickListener) {
//				// TODO Auto-generated method stub
//				return null;
//			}
//       });
//       builder.show();
	}

	public void onDestroy() {
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());

	}

	public boolean checkInternetConnection() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		if (cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isAvailable()
				&& cm.getActiveNetworkInfo().isConnected()) {
			return true;

		} else {
			return false;
		}
	}
}
